package com.atguigu.gulimall.cart.controller;

import com.atguigu.common.constant.CartConstant;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.CartItemVo;
import com.atguigu.gulimall.cart.vo.CartVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class CartController {

    @Resource
    private CartService cartService;

    @RequestMapping("/deleteItem")
    public String deleteItem(Long skuId) {

        cartService.deleteItem(skuId);
        return CartConstant.REDIRECT_CART_BASE_DOMAIN_URL + "/cart.html";
    }


    @RequestMapping("/changeNumItem")
    public String changeNumItem(Long skuId, Integer num) {

        cartService.changeNumItem(skuId, num);
        return CartConstant.REDIRECT_CART_BASE_DOMAIN_URL + "/cart.html";
    }


    @RequestMapping("/checkItem")
    public String checkItem(Long skuId, Integer checked) {

        cartService.checkItem(skuId, checked);
        return CartConstant.REDIRECT_CART_BASE_DOMAIN_URL + "/cart.html";
    }

    @RequestMapping("/cart.html")
    public String cartListPage(Model model) {

        CartVo cart = cartService.getCart();
        model.addAttribute("cart", cart);
        return "cartList";
    }


    @RequestMapping("/addToCart.html")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes redirectAttributes) {
        cartService.addToCart(skuId, num);
        redirectAttributes.addAttribute("skuId", skuId);
        return CartConstant.REDIRECT_CART_BASE_DOMAIN_URL + "/addToCartSuccess.html";
    }


    @RequestMapping("/addToCartSuccess.html")
    public String addToCartSuccess(@RequestParam("skuId") Long skuId, Model model) {
        CartItemVo item = cartService.getCartItem(skuId);
        model.addAttribute("item", item);
        return "success";
    }

    /**
     * 根据客户号获取 购物车信息
     *
     * @param memberId 客户号
     * @return 购物车信息(最新价格)
     */
    @RequestMapping("/{memberId}/cartItems")
    @ResponseBody
    public List<CartItemVo> cartItemsByMemberId(@PathVariable("memberId") Long memberId) {
        return cartService.cartItemsByMemberId(memberId);
    }
}
